<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2021-05-25
 * Time: 上午10:27:11
 * Info: 后台操作日志中间件
 */

namespace app\admin\middleware;

use app\common\model\AuthRule as AuthRuleModel;
use app\common\model\SystemLog as SystemLogModel;

class SystemLog
{

    /**
     * 敏感信息字段，日志记录时需要加密
     * @var array
     */
    protected $sensitiveParams = [
        'password',
        'password_again',
    ];

    public function handle($request, \Closure $next)
    {
        $expire_time = session('admin.expire_time');
        $addTimes    = 3600 * 2;
        if (time() - $expire_time < 300) {
            session('admin.expire_time', $expire_time + $addTimes);
        }
        if ($request->isAjax()) {
            $method = strtolower($request->method());
            //获取后台配置：是否开启后台操作日志
            $operation_log_admin = get_config('operation_log_admin');
            if ( ! $operation_log_admin) {
                return $next($request);
            }
            if (in_array($method, ['post', 'put', 'delete'])) {
                $url    = $request->pathinfo();
                $ext    = $request->ext();
                $ip     = get_client_ip();
                $params = $this->input();
                if (isset($params['s'])) {
                    unset($params['s']);
                }
                if ( ! empty($params)) {
                    foreach ($params as $key => $val) {
                        in_array($key, $this->sensitiveParams) && $params[$key] = cmf_password($val);
                    }
                } else {
                    $params = [];
                }

                $node  = explode('.'.$ext, $url)[0];
                $title = AuthRuleModel::where('node', $node)->value('title');

                $data = [
                    'admin_id'    => cmf_get_admin_id(),
                    'url'         => $url,
                    'title'       => $title,
                    'method'      => $method,
                    'ip'          => $ip,
                    'content'     => json_encode($params, JSON_UNESCAPED_UNICODE),
                    'useragent'   => $_SERVER['HTTP_USER_AGENT'],
                    'create_time' => time(),
                ];
                SystemLogModel::addData($data);
            }
        }

        return $next($request);
    }

    private function input()
    {
        $post = file_get_contents('php://input');
        if (strpos($post, '=')) {
            parse_str($post, $data);
            $post = $data;
        } else {
            $post = json_decode($post, true);
        }

        return $post;
    }

}
